package com.tencent.wxpay.demo.service.impl;

import com.tencent.wxpay.WXPay;
import com.tencent.wxpay.common.Configure;
import com.tencent.wxpay.demo.listener.ResultListener;
import com.tencent.wxpay.demo.service.RefundService;
import com.tencent.wxpay.demo.util.TestUtil;
import com.tencent.wxpay.protocol.request.RefundReqData;
import com.tencent.wxpay.protocol.response.RefundResData;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class RefundServiceImpl implements RefundService {

    @Override
    public RefundResData doRefund(String outTradeNo) {
        DateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 退款单号
        String outRefundNo = sf.format(new Date());
        try{
            // TODO 测试的时候，每次付款都是一分钱，因此这里写了两个1，写死了，用的时候请自行更改
            // TODO 退款的时候，若没写 refund_account 字段，默认使用未结算资金退款，但可能回失败，报未结算金额不足，请从余额退款，这时候应该重新请求，带上refund_account字段，设置值为REFUND_SOURCE_RECHARGE_FUNDS，这里为了测试通过，直接用了余额退款
            RefundReqData refundReqData = new RefundReqData(null,outTradeNo,outRefundNo,1,1,Configure.getMchid(),"REFUND_SOURCE_RECHARGE_FUNDS");
            RefundResData refundResData = WXPay.doRefundBusiness(refundReqData,new ResultListener<RefundResData>());
            return refundResData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        if(TestUtil.init()){
            try{
                RefundService refundService = new RefundServiceImpl();
                RefundResData refundResData = refundService.doRefund("20161014112011");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
